package main

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/robfig/cron"
	"influxdbDemoData/influxdb"
	"influxdbDemoData/irv3"
	"influxdbDemoData/sysinit"
	"influxdbDemoData/util"
	"log"
	"strconv"
	"time"
)

var influxdbConnect *influxdb.Connect
var timeExec TimeExec
var dateTimeFormat = "2006-01-02"

type TimeExec struct {
	Status    string
	StartTime string
	EndTime   string
	Cron      string
}

func main() {
	log.Println("====== main start ======")
	ch := make(chan int, 1)
	initConf()
	RunFunc()
	if timeExec.Status == "true" {
		timeIntervalExec(timeExec.StartTime, timeExec.EndTime)
	}
	for {
		<-ch
	}
	log.Println("====== main exit ======")
}

func RunFunc() {
	c := cron.New()
	c.AddFunc(timeExec.Cron, func() {
		today := time.Now().Format(dateTimeFormat)
		log.Println(fmt.Sprintf("today %v", today))
		physizExec(today)
	})
	c.Start()
	log.Println(fmt.Sprintf("cron %+v", timeExec.Cron))
}

func timeIntervalExec(startTime, endTime string) {
	for _, date := range util.ComputeTime(startTime, endTime) {
		physizExec(date)
	}
}

func physizExec(date string) {
	log.Println(fmt.Sprintf("date: %v", date))
	data, err := irv3.SelectPhysicalData(date)
	if err != nil {
		log.Println(err)
		return
	}
	var flows []influxdb.Flow
	for _, d := range *data {
		flow := influxdb.Flow{
			Time:       d.DateTime,
			ZoneId:     strconv.Itoa(d.CameraZoneId),
			CountEnter: d.CountIn,
			CountExit:  d.CountOut,
		}
		flows = append(flows, flow)
	}
	log.Println(fmt.Sprintf("flows: %v", len(flows)))
	insert := influxdbConnect.InsertPassengerflow(&flows, influxdb.Passengerflow_physicalzone)
	log.Println(fmt.Sprintf("insert: %v", insert))
}

func dateExec(date string) {
	log.Println(fmt.Sprintf("date: %v", date))
	ids, err := irv3.SelectDeviceZoneId()
	if err != nil {
		log.Println(err)
		return
	}
	array := util.SplitArray(ids, 10)
	for _, zoneIds := range array {
		log.Println(fmt.Sprintf("%v", zoneIds))
		exec(date, zoneIds)
	}

}

func exec(date string, deviceZoneIds []int) {

	data, err := irv3.SelectDeviceZoneData_new(deviceZoneIds, date)
	if err != nil {
		log.Println(err)
		return
	}
	var flows []influxdb.Flow
	var flowsBusiness []influxdb.Flow
	for _, d := range *data {
		flow := influxdb.Flow{
			Time:       d.DateTime,
			ZoneId:     strconv.Itoa(d.CameraZoneId),
			CountEnter: d.CountIn,
			CountExit:  d.CountOut,
		}
		flows = append(flows, flow)
		start, err := time.ParseInLocation(util.LayoutDateTime, fmt.Sprintf("%v %v", date, "09:00:00"), time.Local)
		if err != nil {
			panic(err)
		}
		end, err := time.ParseInLocation(util.LayoutDateTime, fmt.Sprintf("%v %v", date, "22:00:00"), time.Local)
		if err != nil {
			panic(err)
		}
		if !d.DateTime.Before(start) && !d.DateTime.After(end) {
			flowsBusiness = append(flowsBusiness, flow)
		}
	}

	log.Println(fmt.Sprintf("flows: %v", len(flows)))
	insert := influxdbConnect.InsertPassengerflow(&flows, influxdb.Passengerflow)
	log.Println(fmt.Sprintf("insert: %v", insert))
	insert_bussiness := influxdbConnect.InsertPassengerflow(&flowsBusiness, influxdb.PassengerflowBusiensss)
	log.Println(fmt.Sprintf("business: %v", insert_bussiness))

}
func execBak(date string) {
	log.Println(fmt.Sprintf("date: %v", date))
	dzs, err := irv3.FindAllFkDeviceZone()
	if err != nil {
		panic(err)
	}
	var deviceZoneIds []int = make([]int, len(*dzs))
	for index, value := range *dzs {
		deviceZoneIds[index] = value.Id
	}
	data, err := irv3.SelectDeviceZoneData(deviceZoneIds, date)

	if err == nil {
		var flows []influxdb.Flow
		var flowsBusiness []influxdb.Flow
		for _, d := range *data {
			flow := influxdb.Flow{
				Time:       d.DateTime,
				ZoneId:     strconv.Itoa(d.CameraZoneId),
				CountEnter: d.CountIn,
				CountExit:  d.CountOut,
			}
			flows = append(flows, flow)
			start, err := time.ParseInLocation(util.LayoutDateTime, fmt.Sprintf("%v %v", date, d.StartTime), time.Local)
			if err != nil {
				panic(err)
			}
			end, err := time.ParseInLocation(util.LayoutDateTime, fmt.Sprintf("%v %v", date, d.EndTime), time.Local)
			if err != nil {
				panic(err)
			}
			if !d.DateTime.Before(start) && !d.DateTime.After(end) {
				flowsBusiness = append(flowsBusiness, flow)
			}
		}

		log.Println(fmt.Sprintf("flows: %v", len(flows)))
		insert := influxdbConnect.InsertPassengerflow(&flows, influxdb.Passengerflow)
		log.Println(fmt.Sprintf("insert: %v", insert))
		insert_bussiness := influxdbConnect.InsertPassengerflow(&flowsBusiness, influxdb.PassengerflowBusiensss)
		log.Println(fmt.Sprintf("business: %v", insert_bussiness))
	} else {
		log.Println(err)
	}
}

func initConf() {
	beego.LoadAppConfig("ini", "conf/app-irv3.conf")
	sysinit.InitDatabase([]string{"ir_v3", "irv3"})
	sysinit.InitLogs()
	//创建链接Influxdb
	iaddr := beego.AppConfig.String("influxdb::addr")
	ipassword := beego.AppConfig.String("influxdb::password")
	iusername := beego.AppConfig.String("influxdb::username")
	idbname := beego.AppConfig.String("influxdb::dbname")
	itimezone := beego.AppConfig.String("influxdb::timezone")

	influxdbConnect = influxdb.NewConnect(iaddr, iusername, ipassword, idbname, itimezone)

	//TimeInterval
	timeExec.Status = beego.AppConfig.String("timeInterval::status")
	timeExec.StartTime = beego.AppConfig.String("timeInterval::start_time")
	timeExec.EndTime = beego.AppConfig.String("timeInterval::end_time")
	timeExec.Cron = beego.AppConfig.String("timeInterval::cron")
}
